package org.geektimes.web.mvc;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang.StringUtils;
import org.geektimes.common.util.ResponseHandlerUtil;
import org.geektimes.injection.annotation.RequestBody;
import org.geektimes.injection.component.ControllerComponent;
import org.geektimes.injection.context.ComponentContext;
import org.geektimes.injection.stream.StringConvertEnum;
import org.geektimes.injection.stream.StringConvertFunction;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @FileName: DefaultControllerServlet
 * @Description: 请求分发处理器
 * @Author: MaWenHao
 * @Created: 2021/2/28 - 下午9:35
 */
public class DefaultControllerServlet extends HttpServlet {

    /**
     * 请求路径和 {@link ControllerComponent} 映射关系缓存
     */
    private Map<String, ControllerComponent> handleComponentMapping = new HashMap<>();

    /**
     * 初始化Controller
     *
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        intiHttpMethod();
    }

    /**
     * 加载application.properties文件中controllerClassNames属性配置的所有Controller
     */
    private void intiHttpMethod() {
        ComponentContext componentContext = ComponentContext.getInstance();
        handleComponentMapping = componentContext.getControllerContainer();

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求映射路径
        String requestURI = req.getRequestURI();
        String contextPath = req.getContextPath();
        String requestMappingPath = StringUtils.substringAfter(requestURI,
                StringUtils.replace(contextPath, "//", "/"));

        ControllerComponent controllerComponentBean = handleComponentMapping.get(requestMappingPath);
        if (Objects.isNull(controllerComponentBean)) {
            // HTTP 未找到对应的处理器
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        if (!controllerComponentBean.getSupportedHttpMethods().contains(req.getMethod())) {
            // HTTP 不支持的方法  
            resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }

        // 处理请求
        try {
            handler(req, resp, controllerComponentBean);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理请求
     *
     * @param req
     * @param resp
     * @param controllerComponentBean 包含处理器相关信息
     */
    private void handler(HttpServletRequest req,
                         HttpServletResponse resp,
                         ControllerComponent controllerComponentBean) throws Exception {
        Method handlerMethod = controllerComponentBean.getHandlerMethod();
        // 参数适配
        Parameter[] methodParameters = handlerMethod.getParameters();
        Object[] parameters = new Object[methodParameters.length];
        Map<String, String[]> requestParameterMap = req.getParameterMap();
        Map<String, String> requestParameterMapMapping = requestParameterMapMapping(requestParameterMap);
        for (int i = 0; i < methodParameters.length; i++) {
            Parameter methodParameter = methodParameters[i];
            Object arg = null;
            RequestBody requestBody = methodParameter.getAnnotation(RequestBody.class);
            if (Objects.nonNull(requestBody)) {
                arg = methodParameter.getType().newInstance();
                BeanUtil.copyProperties(requestParameterMapMapping, arg);
            } else {
                String argName = methodParameter.getName();
                String[] values = requestParameterMap.get(argName);
                String typeName = methodParameter.getParameterizedType().getTypeName();
                StringConvertFunction<Object> converter = StringConvertEnum.getConverter(typeName);
                arg = converter.apply(values);
            }
            parameters[i] = arg;
        }

        // 参数校验
        ComponentContext componentContext = ComponentContext.getInstance();
        Validator validator = componentContext.getBean(Validator.class.getSimpleName());
        if (ObjectUtil.isNotEmpty(validator)) {
            for (Object parameter : parameters) {
                Set<ConstraintViolation<Object>> validations = validator.validate(parameter);
                for (ConstraintViolation<Object> validation : validations) {
                    String message = validation.getMessage();
                    if (StrUtil.isNotBlank(message)) {
                        ResponseHandlerUtil.responseJsonHandle(message, req, resp);
                        return;
                    }
                }
            }
        }

        // 执行目标方法
        Object invoke = handlerMethod.invoke(controllerComponentBean.getBean(), parameters);
        // 处理应答
        controllerComponentBean.getResponseHandler().accept(invoke, req, resp);
    }

    private Map<String, String> requestParameterMapMapping(Map<String, String[]> requestParameterMap) {
        Map<String, String> mapping = new HashMap<>();
        for (Map.Entry<String, String[]> entry : requestParameterMap.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            mapping.put(key, value[0]);
        }
        return mapping;
    }
}
